package com.ClothingStorePOS.controller;

import com.ClothingStorePOS.pojo.*;
import com.ClothingStorePOS.services.IClothesService;
import com.ClothingStorePOS.services.IPayService;
import com.ClothingStorePOS.services.ISaleService;
import com.ClothingStorePOS.shiro.ShiroUser;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/sale")
public class SaleController {

    @Resource(name = "clothesService")
    private IClothesService clothesService;

    @Resource(name = "saleService")
    private ISaleService saleService;

    @Resource(name = "payService")
    private IPayService payService;

    /**
     * 开启一次新的销售
     * @param session
     * @return
     */
    @RequestMapping("/makeNewSale")
    @ResponseBody
    public Result makeNewSale(HttpSession session){
        //获取操作订单的员工的id
        ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
        Result result = new Result();
        //创建订单并存进session
        if (session.getAttribute("ORDER_SESSION")!=null){
            result.setMsg("存在未处理订单，请先处理！");
            result.setSuccess(false);
        }else {
            Order order = new Order(user.loginName);
            /*        System.out.println("操作员id为："+user.getId());*/
            session.setAttribute("ORDER_SESSION", order);
            result.setSuccess(true);
            result.setMsg("成功创建一个新订单，开启新的销售！");
        }
        return result;

    }

    /**
     * 获取session的订单清单
     */
    @RequestMapping("/findOrderItem")
    @ResponseBody
    public Object findOrderItem(HttpSession session){
        List<OrderItem> orderItemList = (List<OrderItem>)session.getAttribute("OrderItemList_SESSION");
        Order order = this.saleService.selectOrderByOrderId(orderItemList.get(0).getOrderid());
        System.out.println(orderItemList.get(0).getOrderid());
        session.setAttribute("ORDER_SESSION",order);
        System.out.println(order.getAmount());
        Map orderItemMap = new HashMap();
/*        if (orderItemList==null){
            for (int i=1;i<11;i++){
                OrderItem orderItem = new OrderItem();
                orderItem.setClothesid(" ");
                orderItem.setClothesname(" ");
                orderItem.setNum(0);
                orderItem.setPrice(0.0);
                orderItemList.add(orderItem);
            }
        }*/
            orderItemMap.put("code", 0);
            orderItemMap.put("msg", "");
            orderItemMap.put("count", orderItemList.size());
            orderItemMap.put("data", orderItemList);
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(orderItemMap));
            System.out.println(jsonObject);
            return jsonObject;
    }

    /**
     * 获取前端的销售记录，查找商品名并返回结果
     */
    @RequestMapping("/addOrderItem")
    @RequiresPermissions("sale:addOrderItem")
    @ResponseBody
    public Object addSaleItem(String clothesid, Integer num, HttpSession session){
        System.out.println("数量为："+num);

        //获取订单
        Order order = (Order) session.getAttribute("ORDER_SESSION");
        Clothes clothes = this.clothesService.searchById(clothesid);
        OrderItem orderItem = new OrderItem(clothes,num);
/*        System.out.println("获得的商品名为："+orderItem.getClothesname());
        System.out.println("数量为："+orderItem.getNum());*/
        ArrayList<OrderItem> orderItemList=order.getOrderItemList();
/*        if(session.getAttribute("OrderItemList_SESSION")==null){
            orderItemList.add(orderItem);
            order.setOrderItemList(orderItemList);
            System.out.println("总金额为："+order.getAmount());
            session.setAttribute("OrderItemList_SESSION",orderItemList);
            session.setAttribute("ORDER_SESSION",order);
        }else{
            orderItemList = (ArrayList<OrderItem>)session.getAttribute("OrderItemList_SESSION");*/
            //若添加的产品已存在，则添加数量，避免重新添加一条新的记录
            for (OrderItem oi:
                    orderItemList ) {
                if (oi.getClothesid().equals(clothesid)){
                    System.out.println("相同商品的数量"+(num+oi.getNum()));
                    orderItem.setNum(num+oi.getNum());
                    orderItem.calSubtotal();
                    System.out.println("orderItem的小计为："+orderItem.getSubtotal());
                    orderItemList.remove(oi);
                    break;
                }
                }

            orderItemList.add(orderItem);
            order.setOrderItemList(orderItemList);
            System.out.println("总金额为："+order.getAmount());
            session.setAttribute("OrderItemList_SESSION",orderItemList);
            session.setAttribute("ORDER_SESSION",order);

        //转化为json格式
        //JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(orderItemList));
        JSONArray result = JSONArray.parseArray(JSON.toJSONString(orderItemList));
        return result;

    }


    /**
     * 删除购物请单的一条
     * @param session
     * @return
     */
    @RequestMapping("/delSaleItem")
    @ResponseBody
    public Object delSaleItem(String clothesId,HttpSession session){
        //获取订单
        Order order = (Order) session.getAttribute("ORDER_SESSION");
        //获取订单清单
        ArrayList<OrderItem> orderItemList=order.getOrderItemList();
        //遍历orderItemList，查找对应的条目并删除
        for (OrderItem orderItem:
             orderItemList) {
            if(orderItem.getClothesid().equals(clothesId)){
                orderItemList.remove(orderItem);
                break;
            }
        }
        System.out.println("orderItemList的数量"+orderItemList.size());
        //将order、orderItemList存进session
        order.setOrderItemList(orderItemList);
        session.setAttribute("ORDER_SESSION",order);
        session.setAttribute("OrderItemList_SESSION",orderItemList);

        //将订单订单数组转化为json格式，并返回给前端
        JSONArray result = JSONArray.parseArray(JSON.toJSONString(orderItemList));
        return result;
    }

    /**
     * 修改数量
     */
    @RequestMapping("/editNum")
    @ResponseBody
    public Object editNum(String clothesid,Integer num,HttpSession session){
        //获取订单
        Order order = (Order) session.getAttribute("ORDER_SESSION");
        //获取订单清单
        ArrayList<OrderItem> orderItemList=order.getOrderItemList();

        Clothes clothes = this.clothesService.searchById(clothesid);
        OrderItem orderItem = new OrderItem(clothes,num);


        //遍历orderItemList，删除原来的记录，并将新的记录加入到orderItemList
        for (OrderItem oi:
                orderItemList ) {
            if (oi.getClothesid().equals(orderItem.getClothesid())){
                System.out.println("修改后的商品数量"+(orderItem.getNum()));
                System.out.println("修改的商品id为"+orderItem.getClothesid());
                orderItemList.remove(oi);
                orderItemList.add(orderItem);
                break;
            }
        }

        //将order、orderItemList存进session
        order.setOrderItemList(orderItemList);
        session.setAttribute("ORDER_SESSION",order);
        session.setAttribute("OrderItemList_SESSION",orderItemList);

        JSONArray result = JSONArray.parseArray(JSON.toJSONString(orderItemList));
        return result;
    }


    /**
     * 挂单操作，存储订单
     * @return
     */
    @RequestMapping("/pendingOrder")
    @ResponseBody
    public Result pendingOrder(String phone,HttpSession session){
        Order order = (Order)session.getAttribute("ORDER_SESSION");
        ArrayList<OrderItem> orderItemList = (ArrayList<OrderItem>)session.getAttribute("OrderItemList_SESSION");
        //添加顾客手机号码
        order.setPhone(phone);
        //将订单状态设置为未完成
        order.setStatus(1);
        this.chargeTheSame(order,orderItemList);

        session.removeAttribute("ORDER_SESSION");
        session.removeAttribute("OrderItemList_SESSION");
        Result result = new Result();
        result.setSuccess(true);
        result.setMsg("挂单成功！");
        return result;
    }

    /**
     * 全单取消
     */
    @RequestMapping("/cancelOrder")
    @ResponseBody
    public Result cancelOrder(HttpSession session){
        session.removeAttribute("ORDER_SESSION");
        session.removeAttribute("OrderItemList_SESSION");
        System.out.println("全单取消！"+session.getAttribute("ORDER_SESSION"));
        Result result = new Result();
        result.setSuccess(true);
        result.setMsg("全单取消成功！");
        return result;
    }

    /**
     * 查询所有挂单订单
     */

    /**
     * 跳转到支付页面
     */
    @RequestMapping("/toPayPage")
    public String toPayPage(HttpSession session){
        if (session.getAttribute("OrderItemList_SESSION")!=null){
            return "/payPage";
        }
        return null;
    }

    /**
     *订单结算
     * @param session
     * @return
     */
    @RequestMapping("/chargeMoney")
    @ResponseBody
    public Result chargeMoney(Byte payStyle,HttpSession session){

        Order order = (Order)session.getAttribute("ORDER_SESSION") ;
        ArrayList<OrderItem> orderItemList = (ArrayList<OrderItem>)session.getAttribute("OrderItemList_SESSION");
        order.isCompleted();
        this.chargeTheSame(order,orderItemList);

        //将支付添加到支付表
        Pay pay = new Pay(order.getId(),order.getAmount(),payStyle);
        this.payService.insertPay(pay);

        session.removeAttribute("ORDER_SESSION");
        session.removeAttribute("OrderItemList_SESSION");
        Result result = new Result();
        result.setSuccess(true);
        result.setMsg("结算成功");
        return result;

    }

    /**
     * 对挂单的订单，取单后进行相同商品的更新和不同商品的添加
     * @param order
     * @param orderItemList
     */
    public void chargeTheSame(Order order,ArrayList<OrderItem> orderItemList){
        Order oldOrder = this.saleService.selectOrderById(order.getId());
        int flag=0;
        if (oldOrder!=null) {
            ArrayList<OrderItem> oldOrderItemList = oldOrder.getOrderItemList();
            Map map = new HashMap<OrderItem,Integer>();
            this.saleService.updateOrderByOrderId(order);
/*            if (oldOrderItemList.size()<=orderItemList.size()) { //对于原来的清单商品种类有增加*/
                for (OrderItem orderItem :
                        orderItemList) {
                    for (OrderItem oldOrderItem :
                            oldOrderItemList) {
                        if (oldOrderItem.getId() == orderItem.getId()) {
                            this.saleService.updateOrderItem(orderItem);
                            flag = 1;
                            map.put(oldOrderItem,1);
                            break;
                        }
                    }
                    if (flag == 1)
                        continue;
                    else {
                        orderItem.setOrderid(order.getId());
                        this.saleService.insertOrderItem(orderItem);
                        continue;
                    }
                }

            for (OrderItem oldItem ://删除取单后删除的条目
                    oldOrderItemList
                 ) {
                if (map.get(oldItem)==null)
                    this.saleService.delByItemId(oldItem.getId());
            }
        }else {
            //将订单插入订单表
            this.saleService.insertNewOrder(order);
            //获取订单明细并插入明细表

            for (OrderItem orderItem :
                    orderItemList) {
                orderItem.setOrderid(order.getId());
                this.saleService.insertOrderItem(orderItem);
            }
        }
    }

}
